<?php

namespace App\Utils\Filter\Admin\System;

use App\Entity\NoticeRead;
use App\Utils\Base\FilterBase;
use App\Utils\Enum\NoticeEnum;
use App\Utils\Helper\GetterHelper;

class NoticeFilter extends FilterBase {
    public function noticeTypeId ($field, $value) {
        $this->builder->andwhere($field.' = :notice_type_id')->setParameter('notice_type_id', $value);
    }

    public function title ($field, $value) {
        $this->builder->andwhere($field.' like :title')->setParameter('title', '%'.$value.'%');
    }

    public function toType ($field, $value) {
        $admin_user_group_id = $value['admin_user_group_id'] ?? 0;
        $admin_user_id = $value['admin_user_id'] ?? 0;
        $query = $this->builder->expr()->orX();
        // 全部
        $orAll = $this->builder->expr()->andX();
        $orAll->add($this->builder->expr()->eq(FilterBase::ALIAS.'.to_type', NoticeEnum::TO_TYPE_ALL));
        // 用户组
        $orUserGroup = $this->builder->expr()->andX();
        $orUserGroup->add($this->builder->expr()->eq(FilterBase::ALIAS.'.to_type', NoticeEnum::TO_TYPE_USER_GROUP));
        $orUserGroup->add($this->builder->expr()->andX("JSON_CONTAINS(".FilterBase::ALIAS.".to_id, '[".$admin_user_group_id."]', '$') = 1"));
        // 用户
        $orUser = $this->builder->expr()->andX();
        $orUser->add($this->builder->expr()->eq(FilterBase::ALIAS.'.to_type', NoticeEnum::TO_TYPE_USER));
        $orUser->add($this->builder->expr()->andX("JSON_CONTAINS(".FilterBase::ALIAS.".to_id, '[".$admin_user_id."]', '$') = 1"));
        $query->add($orAll)->add($orUserGroup)->add($orUser);
        $this->builder->andWhere($query);
    }

    public function unreadNotice ($field, $value) {
        $admin_user_id = $value['admin_user_id'] ?? 0;
        $read_notice_ids = GetterHelper::getEntityManager()->getRepository(NoticeRead::class)->getReadNoticesIds($admin_user_id);
        if ($read_notice_ids) {
            $this->builder->andWhere(FilterBase::ALIAS.'.id not in ('.implode(',', $read_notice_ids).')');
        }
    }

    public function readStatus ($field, $value) {
        $status = $value['value'] ?? 0;
        $notice_ids = $value['notice_ids'] ?? [];
        if ($notice_ids) {
            if ($status) {
                $this->builder->andWhere(FilterBase::ALIAS.'.id in ('.implode(',', $notice_ids).')');
            } else {
                $this->builder->andWhere(FilterBase::ALIAS.'.id not in ('.implode(',', $notice_ids).')');
            }
        }
    }

    public function date ($field, $value) {
        if (is_array($value) && count($value) == 2) {
            $start = $value[0].' 00:00:00';
            $end = $value[1].' 23:59:59';
            $this->builder->andwhere($this->builder->expr()->between(FilterBase::ALIAS.'.created_at', "'".$start."'", "'".$end."'"));
        }
    }
}